package com.jgzx.security.advice;

import com.alibaba.fastjson.JSON;
import com.jgzx.common.R;
import com.jgzx.security.annotation.PortalEncrypt;
import com.jgzx.utils.PortalEncryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Objects;

/**
 * 响应平台参数加密AOP
 * @author libo
 * @date 2021/7/30 20:15
 */
@Slf4j
@ControllerAdvice
public class PortalEncryptResponseAdvice implements ResponseBodyAdvice<Object> {

    private boolean encrypt;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if (Objects.requireNonNull(returnType.getMethod()).isAnnotationPresent(PortalEncrypt.class)) {
            encrypt = true;
        } else {
            encrypt = false;
        }
        return encrypt;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (encrypt) {
            try {
                R r = JSON.parseObject(JSON.toJSONString(body), R.class);
                String content = JSON.toJSONString(r.getData());
                String encryptContent = PortalEncryptUtil.aesEncrypt(content);
                log.info("未加密数据：{}，加密后数据：{}", content, encryptContent);
                r.setData(encryptContent);
                return r;
            } catch (Exception e) {
                log.error("加密数据异常", e);
                return R.fail("加密数据异常");
            }
        }
        return body;
    }
}
